package com.gollum.system.service.impl;

import cn.hutool.core.lang.tree.Tree;
import com.gollum.common.enums.GollumStatus;
import com.gollum.common.utils.TreeUtils;
import com.gollum.jpa.common.Specifications;
import com.gollum.jpa.service.JpaServerImpl;
import com.gollum.jpa.util.QueryUtils;
import com.gollum.system.domain.dao.SysDeptDao;
import com.gollum.system.domain.model.SysDept;
import com.gollum.system.service.SysDeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import java.util.List;

import static com.gollum.common.constant.NumberConstants.ZERO_STR;

/**
 * 组织机构service 实现
 *
 * @author Herther
 * @createTime 2022年10月11日 00:03:00
 * @since 1.0.0
 */
@Service
public class SysDeptServiceImpl  extends JpaServerImpl<SysDept,Long> implements SysDeptService {

    @Autowired
    protected SysDeptDao sysDeptDao;

    /** 根据orderNum 排序 **/
    private final String ORDERS = "orderNum:desc";

    @Override
    public List<Tree<String>> getTreeList() {
        Specification<SysDept> findParams = Specifications.<SysDept>and()
                .eq(SysDept::getStatus, GollumStatus.OK.getValue()).build();
        Sort orders =
                QueryUtils.buildSort(ORDERS);

        return buildTree(sysDeptDao.findAll(findParams, orders));
    }

    /**
     *
     * 构建前端搜索树组织架构
     *
     * @param sysDept
     * @return List<Tree<String>>
     * @author Herther
     * @since 1.0.0
     * @date: 2022/09/19 0:01
     */
    private List<Tree<String>> buildTree(List<SysDept> sysDept){
        //转换器
        List<Tree<String>> treeNodes = TreeUtils.build(sysDept, ZERO_STR, TreeUtils.getTreeComponentNodeConfig(),
                (treeNode, tree) -> {
                    tree.setId(treeNode.getId().toString());
                    tree.setParentId(treeNode.getParentId().toString());
                    tree.setWeight(treeNode.getOrderNum());
                    tree.setName(treeNode.getDeptName());
                    // 父节点不让选中 --配合前端
                    //tree.putExtra(TreeUtils.TreeConstants.SELECTABLE, treeNode.getParentId() == 0 ? false : true);
                });
        return treeNodes;
    }
}
